/*
* dataview 私有方法  编辑页面
* */
import utilVuex from '../../utilVuex.js'

const dvFunPrivateForm = {
  // 编辑界面按钮事件
  handleViewFormButton(button, data) {
    if (!this._propBeforeClick(button, data , null)) {
      return
    }
    const {afterClick} = this.viewFormEvents
    switch (button.key) {
    case 'vfb-add':
      this.viewFormAdd()
      break
    case 'vfb-save': {
      this.viewFormSave()
      break
    }
    case 'vfb-cancel':
      this.viewFormCancel()
      break
    case 'vfb-delete':
      this.viewFormDelete()
      break
    default:
      if (button.flagPrint && button.flagPrint == true) { //标准打印按钮
        if (this.strings.isBlank(button.printBusType)) {
          this.utilMessage.warning('该打印按钮未配置打印模板，请检查')
          return
        }
        let param = {
          'that': this, //当前调用对象
          configList: [ //打印配置，可以多个
            {
              //打印配置
              printBusType: button.printBusType, //打印业务类型，来源print_template.bus_type，同constPrint.busKey
              //主单据数据或者数据查询配置
              formData: this.viewFormData, //数据对象
              formDataId: this.viewFormData.id,
            }
          ]
        }
        global.utilPrint.openFormPrint(param)
      } else {
        if (afterClick) {
          afterClick(button, data, this && this.$refs && this.$refs.viewForm ? this.$refs.viewForm : this.$refs.viewForm)
        }
      }
    }
  },
  // 生成用户查询数据
  makeUserQuery(isUpdate) {
    if (this.columns && this.columns.length > 0) {
      this.columns.forEach((o) => this.$set(o, 'value', this.strings.defaultIfBlank(o.value, '')))
      this.userQuery = this.columns.filter((item) => this.strings.isNotBlank(item.queryType) && item.queryType !== 'none')
    }

    //包含列表查询排序的话，则进行排序
    if (this.userQuery && this.userQuery.length > 0 && this.userQuery[0].sortQuery) {
      this.userQuery.sort((left, right) => {
        return this.strings.defaultIfBlank(left.sortQuery, 999) - this.strings.defaultIfBlank(right.sortQuery, 999)
      })
    }

    // 流程状态查询
    if (this.flowNodes.length > 0 && !this.propHidePageSearch && !this.propHideFlowSelect) {
      this.userQuery.unshift({
        hidden: false,
        name: 'flowStatus',
        queryType: 'select',
        sort: 1,
        title: '流程状态',
      })

      this.viewFormDictionaries.flowStatus = this.flowNodes.map(item => {
        return {
          id: item.value,
          name: item.name,
          label: item.name,
        }
      })
    }

    this.tableForm = this.getTableForm(isUpdate)
    setTimeout(() => {
      //查询区域input绑定回车事件
      try {
        if ($(this.$refs.tbMain.$el).find('.el-input__inner').length > 0) {
          $(this.$refs.tbMain.$el).find('.el-input__inner').bind('keydown', (event) => {
            if (event.keyCode == '13') {
              this.handleQueryClick()
            }
          })
        }

        if ($(this.$refs.tbMain.$el).find('.vxe-input--inner').length > 0) {
          $(this.$refs.tbMain.$el).find('.vxe-input--inner').bind('keydown', (event) => {
            if (event.keyCode == '13') {
              this.handleQueryClick()
            }
          })
        }
        // eslint-disable-next-line no-empty
      } catch (e) {
      }
    }, 500)
  },
  //渲染查询组件
  getTableForm(isUpdate) {
    //分组排序字段
    if (this.searchGroupFields && this.searchGroupFields.length > 0) {
      //延迟加载吧，不然有点卡顿的感觉
      this.searchGroupData = []
      let searchGroupFieldsNew = []
      this.searchGroupFields.forEach(field => {
        let group = this.columnsMap[field]
        if (group) {
          if (this.strings.isNotBlank(group.dict)) {
            group.list = this.utils.getDictDataList(group.dict)

            //设置选中
            if (this.searchGroup[field] && this.searchGroup[field].length > 0 && group.list) {
              group.list.filter(ob => this.searchGroup[field].includes(ob.val)).forEach(ob2 => ob2.checked = true)
              group.list.filter(ob => !this.searchGroup[field].includes(ob.val)).forEach(ob2 => ob2.checked = false)
            }
          } else {
            group.list = []
          }
          this.searchGroupData.push(group)
          searchGroupFieldsNew.push(field)
        }
      })
      this.searchGroupFields = searchGroupFieldsNew
    }

    if (this.propHidePageSearch) {
      return {
        data: {

        }
      }
    }
    let data = {}
    let items = []

    // if (this.flagFullTxtSearch) { //数据库全文搜索
    //   data[this.fullSearchKey] = ''
    //   items.push({
    //     title: '全文搜索',
    //     field: this.fullSearchKey,
    //     itemRender: {
    //       name: 'ElInput',
    //       props: {
    //         placeholder: this.flagFullTxtTitle, clearable: true
    //       },
    //       events: {
    //         clear: this.handleQueryClick,
    //       }
    //     }
    //   })
    // }

    //最大标题长度
    let titleMaxLength = 0
    this.userQuery.forEach(q => {
      let titleNew = this.utilFieldMap.show(q.name, q.title, 'dataview', this.propViewKey)
      titleNew = titleNew.replace(/\(/g, '')
      titleNew = titleNew.replace(/\)/g, '')
      if (this.strings.lengthByte(titleNew) > titleMaxLength) titleMaxLength = this.strings.lengthByte(titleNew)
    })
    let titleWidth = titleMaxLength * 10
    if (titleWidth < 40) titleWidth = 40

    let queryFormLabelWidth = this.formConfig && this.formConfig.queryFormLabelWidth ? this.formConfig.queryFormLabelWidth : 0

    if (queryFormLabelWidth > 0) {
      titleWidth = queryFormLabelWidth
    }

    let that2 = this

    this.userQuery.forEach(q => {
      if (this.propHideColumns && this.propHideColumns.includes(q.name)) {
        return true
      }
      data[q.name] = ''
      let name1 = q.name + '1'
      switch (q.queryType) {
      case 'numberArea':
        items.push({
          title: q.title,
          field: q.name,
          titleWidth,
          itemRender: {name: 'ElInputNumber', props: {placeholder: '最小值', size: 'small'}}
        })


        data[name1] = ''
        items.push({
          field: name1,
          titleWidth: '33',
          title: ' ',
          titlePrefix: {
            icon: 'vxe-icon--arrow-left'
          },
          titleSuffix: {
            icon: 'vxe-icon--arrow-right'
          },
          itemRender: {name: 'ElInputNumber', props: {placeholder: '最大值', size: 'small'}}
        })
        break
      case 'dateArea':
        // eslint-disable-next-line no-case-declarations
        let dateType = 'date'
        if (q.datePattern && q.datePattern == 'yyyy-MM-dd HH:mm:ss') dateType = 'datetime'
        items.push({
          title: q.title,
          field: q.name,
          titleWidth,
          itemRender: {
            name: 'ElDatePicker',
            props: {
              type: dateType,
              format: this.strings.defaultString(q.datePattern, 'yyyy-MM-dd'),
              valueFormat: this.strings.defaultString(q.datePattern, 'yyyy-MM-dd'),
              placeholder: '开始'
            },
            events: {
              change: this.handleQueryClick,
              clear: this.handleQueryClick,
            }
          }
        })
        data[name1] = ''
        if (q.name == this.dateFirstName) {
          // data[q.name] = this.tableFormState[q.name]
          // data[name1] = this.tableFormState[name1]
          data[q.name] = this.tableFormState[q.name]
        }
        items.push({
          field: name1,
          titleWidth: '33',
          title: ' ',
          titlePrefix: {
            icon: 'vxe-icon--arrow-left'
          },
          titleSuffix: {
            icon: 'vxe-icon--arrow-right'
          },
          itemRender: {
            name: 'ElDatePicker',
            props: {
              type: dateType,
              format: this.strings.defaultString(q.datePattern, 'yyyy-MM-dd'),
              placeholder: '结束'
            },
            events: {
              change: this.handleQueryClick,
              clear: this.handleQueryClick,
            }
          }
        })
        break
      case 'select':
        //数据视图所配置的默认字段查询条件
        if (this.strings.isNotBlank(q.defaultQuery)) data[q.name] = q.defaultQuery


        // eslint-disable-next-line no-case-declarations
        let options = []
        if (this.strings.isNotBlank(q.sourceVuex)) {  //从状态管理里面获取
          options = utilVuex[q.sourceVuex]()
        }else {
          options = q.dict ? this.utils.getDictDataList(q.dict, this) : this.viewFormDictionaries[q.name] //数据源
        }

        // eslint-disable-next-line no-case-declarations
        let optionProps = {label: 'label', value: 'value'}
        if (options && !q.dict) {
          //非字典，从数据库查询
          optionProps = {label: 'name', value: 'id'}
        }

        if (this.strings.isNotBlank(q.selectUrl)) {  //地址查询
          options = that2.selectUrlData[q.name]
          optionProps = {label: 'label', value: 'value'}
        }

        if (options) {
          options = options.map(op => {
            let label = optionProps.label
            let value = optionProps.value
            return {
              label: op[label], value: op[value]
            }
          })

          // 流程状态特殊处理,根据权限追加流程节点
          if (q.name == 'flowStatus' ) {
            options = []
            if (this.flowNodes.length > 0) {
              this.flowNodes.forEach(flowNode => {
                // 若指定了权限，并且没有指定everyone
                let { roleCodes = [], code, admin} = this.utils.getCurrentUser()

                if (code != 'admin' && !admin &&  this.strings.isNotBlank(flowNode.roleCodes)) {
                  let isHave = false
                  flowNode.roleCodes.forEach(flowRoleCode => {
                    if (roleCodes.includes(flowRoleCode)) {
                      isHave = true
                    }
                  })
                  if (isHave) {
                    options.push(
                      {
                        label: flowNode.name, value: flowNode.value
                      }
                    )
                  }
                } else{
                  options.push(
                    {
                      label: flowNode.name, value: flowNode.value
                    }
                  )
                }
              })
            }

            if (this.tableFormState.flowStatus) data.flowStatus = this.tableFormState.flowStatus
          }
        }

        items.push({
          title: this.utilFieldMap.show(q.name, q.title, 'dataview', this.propViewKey),
          field: q.name,
          titleWidth,
          itemRender: {
            name: 'ElSelect',
            options,
            events: {change: this.handleQueryClick},
            props: {self: this, placeholder: '请选择', filterable: true, clearable: true, options}
          }
        })
        break
      case 'FortenDataviewDown':
        items.push({
          title: this.utilFieldMap.show(q.name, q.title, 'dataview', this.propViewKey),
          field: q.name,
          titleWidth,
          itemRender: {
            name: 'FortenDataviewDownSelect',
            events: {change: this.handleQueryClick},
            props: {self: this, placeholder: '请选择', filterable: true, clearable: true, options}
          }
        })
        break
      default:
        items.push({
          title: this.utilFieldMap.show(q.name, q.title, 'dataview', this.propViewKey),
          field: q.name,
          titleWidth,
          itemRender: {
            name: 'ElInput',
            props: {
              placeholder: '回车搜索', clearable: true
            },
            events: {
              clear: this.handleQueryClick
            },
          }
        })
        break
      }
    })

    if (!this.flagFullTxtSearch && this.propShowFullSearch) { //页面全文搜索
      data[this.pageSearchKey] = ''
      items.push({
        title: '页面搜索',
        field: this.pageSearchKey,
        itemRender: {
          name: 'ElInput',
          events: {input: this.handlePageSearch},
          props: {placeholder: '页面搜索'}
        }
      })
    }

    if (!(isUpdate && isUpdate == true)) {
      items = this.appendOpBtn(items)
    }
    return {data, items}
  },
  //追加查询类按钮
  appendOpBtn(items) {
    let tbWidth = window.innerWidth - 200
    if (this.$refs.tbMain) {
      tbWidth = $(this.$refs.tbMain.$el).width()
    }
    if (this.searchGroupFields && this.searchGroupFields.length > 0) {
      tbWidth -= 150
    }
    //每行最多显示几个查询条件
    let maxNum = Math.ceil(tbWidth / 260)
    if (items.length > maxNum && items.length > 3) {  //查询项数量小于每行最多
      this.viewButtons.unshift({
        key: 'vb-toggle',
        title: '展开查询',
        type: 'default',
        icon: 'el-icon-sort', iconStatic: 'toggle', sort: -80
      })
    }
    if (items.length > 0) {
      this.viewButtons.unshift({
        key: 'vb-search',
        title: '查询',
        type: 'primary',
        icon: 'el-icon-search', iconStatic: 'search', sort: -100
      }, {
        key: 'vb-reset',
        title: '重置',
        type: 'default',
        icon: 'el-icon-refresh-right', iconStatic: 'reset', sort: -90
      })
    }
    return items
  },

  // 显示表单
  formShow() {
    this.$refs.customDrawerForm.show()
  },

  // 隐藏表单
  formHide() {
    if (!this.$refs.customDrawerForm) {
      return
    }
    this.$refs.customDrawerForm.hide()
    this.$emit('close')
    this.isShowCustomDrawerForm = false
  },

  // 表单显示后
  _formShow() {
    if (this.showRow[this.primaryKey]) { //编辑
      // this.utilVue.loadShow(true)
      // setTimeout(() => {
      //   this._refreshCurrentRow(this.showRow, this.showTriggerMove)
      // }, 500)
    } else {//新增
      // this._addnew()
    }
    this.isShowCustomDrawerForm = true
  },

  // 显示操作记录
  formLogShow() {
    this.$refs.customDrawerLog.show()
  },

  // 显示操作意见
  formAuditShow() {
    this.$refs.customDrawerAudit.show()
  },

  // 显示操作意见
  formAuditHide() {
    this.$refs.customDrawerAudit.hide()
  },

  // 编辑弹框隐藏
  customDrawerFormHide() {
    this.viewFormVisible = false
  },

  // 自动保存中
  formAutoSaveing() {
    this.$refs.customDrawerForm.loading()
  },

  // 自动保存成功
  formAutoSaveSuccess() {
    this.$refs.customDrawerForm.loadingSuccess()
  },

  // 自动保存失败
  formAutoSaveError() {
    this.$refs.customDrawerForm.loadingError()
  },

  // 自动保存失败
  formAutoSave() {
    // if (this.cpFormAutoSave) {
    //   this.timerAutoSave = setInterval( () => {
    //     let formData = this.$refs.viewForm.form
    //     console.log('this.formData', formData)
    //     console.log('this.lastSaveData', this.lastSaveData)
    //     let fieldChangeList = Object.keys(this.lastSaveData).filter(key => formData[key] !=  this.lastSaveData[key])
    //     let fieldChangeList2 = Object.keys(formData).filter(key => formData[key] !=  this.lastSaveData[key])
    //     console.log('fieldChangeList', fieldChangeList.join(','))
    //     if (fieldChangeList.length == 0 && fieldChangeList2.length == 0)  {
    //       return;
    //     }
    //     this._validateOnly(() => {
    //       this._viewFormSaveOnly()
    //     })
    //   }, 5000)
    // }
  },

  // 获取表单项的其他属性
  getFormItemAttr(item) {
    let attr = {}
    let config = {}
    let queryType = item.queryType
    let type = this.constCommon.formItemType.inputText.name
    switch(queryType) {
      case "numberArea": { // 数字区间
        type = this.constCommon.formItemType.inputNumber.name
        break
      }
      case "dateArea": { // 日期区间
        type = this.constCommon.formItemType.datePickerRange.name
        break
      }
      case "select": { // 下拉框
        type = this.constCommon.formItemType.selectStatic.name

        let options = []
        if (this.strings.isNotBlank(item.sourceVuex)) {  //从状态管理里面获取
          options = utilVuex[item.sourceVuex]()
        } else if (this.strings.isNotBlank(item.selectUrl)) {  //地址查询
          options = this.selectUrlData[item.name]
        } else {
          options = item.dict ? this.utils.getDictDataList(item.dict, this) : this.viewFormDictionaries[item.name] //数据源
        }
        if (options && options.length != 0) {
          options.forEach(find => {
            if (find.value == undefined) {
              find.value = find.id
            }
            if (find.label == undefined) {
              find.label = find.name
            }
          })
        }
        config.options = options
        break
      }
      default: {

      }
    }
    attr.type = type
    attr.config = config
    return attr
  },

  queryFormItemChange(item) {
    console.log('item', item)
    if ('text' == item.queryType) {
      return
    }
    this.handleQueryClick()
  },
  // 切换
  toggleForm() {
    let form = $(this.$refs.queryFormDataView.$el)
    if (form.hasClass('max-height-auto')) {
      form.removeClass('max-height-auto')
      this.isQueryMore = false
    } else {
      form.addClass('max-height-auto')
      this.isQueryMore = true
    }
  },
  getToolbarButtonTitle(rowButton) {
    if (rowButton.key == 'vb-toggle') {
      return this.isQueryMore ? '折叠条件' : '展开条件'
    }
    return rowButton.name
  }
}

export default dvFunPrivateForm
